import { canNavigate } from '@layouts/plugins/casl';

export const setupGuards = router => {
  // 👉 router.beforeEach
  // Docs: https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
  router.beforeEach(to => {
    /**
    * If it's a public route, continue navigation. This kind of pages are allowed to visited by login & non-login users. Basically, without any restrictions.
    * 如果是公共路由，请继续导航。此类页面允许登录和非登录用户访问。基本上没有任何限制
    * Examples of public routes are, 404, under maintenance, etc.
    * 公共路由的例子有404、维护中等。
    */
    if (to.meta.public)
      return

    /**
    * 通过检查本地存储中是否存在令牌和用户数据来检查用户是否登录
    * 请随意更新此逻辑以满足您的需要
    */
    const userInfo = JSON.parse(window.localStorage.getItem('justech-userInfo'));
    const refreshTokenStr = JSON.parse(window.localStorage.getItem('justech-refreshToken'));
    const isLoggedIn = !!(userInfo && refreshTokenStr)
    /**
    * 如果用户已登录并试图访问类似登录的页面，则重定向到主页，否则允许访问该页面
    * (警告：不允许通过return语句进一步执行，因为下一段代码将检查权限)
    */
    if (to.meta.unauthenticatedOnly) {
      if (isLoggedIn)
        return '/'
      else
        return undefined
    }
    if (!canNavigate(to) && to.matched.length) {
      /* eslint-disable indent */
      return isLoggedIn ? { name: 'not-authorized' } : {
        // name: 'login',
        name: 'authredirect',
        query: {
          ...to.query,
          to: to.fullPath !== '/' ? to.path : undefined,
        },
      }
      /* eslint-enable indent */
    }
  })
}
